using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Globalization;

namespace VisualEsse.DataEngine
{
    public class NcmlDocument
    {
        protected List<CdmDimension> dims;
        protected List<CdmVariable> vars;

        public NcmlDocument()
        {
            dims = new List<CdmDimension>();
            vars = new List<CdmVariable>();
        }

        public int GetDimension(string name)
        {
            foreach (CdmDimension d in dims)
            {
                if (d.Name == name)
                    return d.Length;
            }
            throw new Exception("Dimension " + name + " not found");
        }

        public CdmVariable GetVariable(string name)
        {
            foreach (CdmVariable v in vars)
            {
                if (v.Name == name)
                    return v;
            }
            throw new Exception("Variable " + name + " not found");
        }

        public void Clear()
        {
            dims.Clear();
            vars.Clear();
        }

        public void Load(string filename)
        {
            XmlReader r = null;
            try
            {
                r = XmlReader.Create(filename);
                Load(r);
            }
            finally
            {
                if (r != null)
                    r.Close();
            }
        }

        public void Load(XmlReader reader)
        {
            reader.ReadStartElement("netcdf");

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1)
                {
                    if (reader.LocalName == "dimension")
                    {
                        CdmDimension dim = new CdmDimension(reader);
                        dims.Add(dim);
                    }
                    else if (reader.LocalName == "variable")
                    {
                        CdmVariable var = new CdmVariable(reader);
                        vars.Add(var);
                    }
                }
            }
        }
    }


    public class CdmVariable
    {
        private string name;
        private string shape;
        private string[] dims;
        private string values;
        private Dictionary<string, string> attrs;

        public CdmVariable(XmlReader reader)
        {
            if (reader.Name != "variable")
            {
                if (!reader.ReadToFollowing("variable"))
                    throw new Exception("variable exprected");
            }

            if (!reader.HasAttributes)
                throw new Exception("variable should have attributes");

            this.name = reader.GetAttribute("name");

            shape = reader.GetAttribute("shape");
            if (shape != null)
                dims = shape.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            reader.Read();

            attrs = new Dictionary<string, string>();
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                    if (reader.LocalName == "attribute")
                    {
                        attrs.Add(
                            reader.GetAttribute("name"),
                            reader.GetAttribute("value"));
                    }
                    else break;
            }

            if (!(reader.NodeType == XmlNodeType.Element && reader.LocalName == "values") 
                && !reader.ReadToNextSibling("values"))
                throw new Exception("variable should have values");

            reader.Read();
            values = reader.Value;
        }

        public string GetAttribure(string name)
        {
            if(attrs.ContainsKey(name))
                return attrs[name];
            return null;
        }

        public string Name
        {
            get { return name; }
        }

        public string Values
        {
            get { return values; }
        }

        /// <summary>Returns string describing shape of variable or null for scalar variable. Corresponds to shape 
        /// attribute in NcML. The attribute shape represents an ordered list (blank separated) of the names 
        /// of the dimensions the variable depends on. The dimensions names must be ordered with the most 
        /// rapidly varying dimension last (same as in the CDL description, same as for C multidimensional arrays). 
        /// Scalar variables must omit this attribute.</summary>
        public string Shape
        {
            get { return shape; }
        }

        /// <summary>Returns array of dimensions names or null for scalar variable</summary>
        public string[] Dimensions
        {
            get
            {
                return dims;
            }
        }

        public float[] ParseValues()
        {
            string[] vals = values.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            float[] f = new float[vals.Length];

            for (int i = 0; i < vals.Length; i++)
            {
                f[i] = float.Parse(vals[i], CultureInfo.InvariantCulture);
            }

            return f;
        }

        public bool IsAscendencyOrder
        {
            get
            {
                string[] vals = values.Split(new char[] { ' ' }, 3, StringSplitOptions.None);
                if (vals.Length < 2)
                    return true;

                float a = float.Parse(vals[0], CultureInfo.InvariantCulture);
                float b = float.Parse(vals[1], CultureInfo.InvariantCulture);
                return b > a;
            }
        }
    }

    public class CdmDimension
    {
        private string name;
        private int length;


        public CdmDimension(XmlReader reader)
        {
            if (reader.Name != "dimension")
            {
                if (!reader.ReadToFollowing("dimension"))
                    throw new Exception("dimension exprected");
            }

            if (!reader.HasAttributes)
                throw new Exception("dimension should have attributes");

            this.name = reader.GetAttribute("name");
            this.length = int.Parse(reader.GetAttribute("length"));
            reader.Read();
        }

        public string Name
        {
            get { return name; }
        }

        public int Length
        {
            get { return length; }
        }
    }
}
